using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using AutoStartManager.Models;
using AutoStartManager.Services;

namespace AutoStartManager
{
    public partial class MainForm : Form
    {
        private readonly ConfigManager _configManager;
        private readonly ProcessMonitor _processMonitor;
        private readonly StartupManager _startupManager;
        private List<ManagedApp> _managedApps;
        private bool _autoStartEnabled;

        // UI控件
        private DataGridView _appsDataGridView;
        private Button _addAppButton;
        private Button _removeAppButton;
        private Button _editAppButton;
        private Button _addFromProcessButton;
        private CheckBox _autoStartCheckBox;
        private Button _refreshButton;
        private StatusStrip _statusStrip;
        private ToolStripStatusLabel _statusLabel;
        private NotifyIcon _notifyIcon;
        private TableLayoutPanel mainPanel;
        private Panel toolbarPanel;
        private DataGridViewTextBoxColumn dataGridViewTextBoxColumn1;
        private DataGridViewTextBoxColumn dataGridViewTextBoxColumn2;
        private DataGridViewTextBoxColumn dataGridViewTextBoxColumn3;
        private DataGridViewTextBoxColumn dataGridViewTextBoxColumn4;
        private DataGridViewTextBoxColumn dataGridViewTextBoxColumn5;
        private DataGridViewTextBoxColumn dataGridViewTextBoxColumn6;
        private ContextMenuStrip _notifyContextMenu;

        public MainForm()
        {
            _configManager = new ConfigManager();
            _processMonitor = new ProcessMonitor(_configManager);
            _startupManager = new StartupManager();
            _managedApps = new List<ManagedApp>();

            InitializeComponent();
            LoadConfiguration();
            SetupProcessMonitor();
            SetupNotifyIcon();
        }

        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
            mainPanel = new TableLayoutPanel();
            toolbarPanel = new Panel();
            _addAppButton = new Button();
            _editAppButton = new Button();
            _removeAppButton = new Button();
            _addFromProcessButton = new Button();
            _refreshButton = new Button();
            _autoStartCheckBox = new CheckBox();
            _appsDataGridView = new DataGridView();
            _statusStrip = new StatusStrip();
            _statusLabel = new ToolStripStatusLabel();
            dataGridViewTextBoxColumn1 = new DataGridViewTextBoxColumn();
            dataGridViewTextBoxColumn2 = new DataGridViewTextBoxColumn();
            dataGridViewTextBoxColumn3 = new DataGridViewTextBoxColumn();
            dataGridViewTextBoxColumn4 = new DataGridViewTextBoxColumn();
            dataGridViewTextBoxColumn5 = new DataGridViewTextBoxColumn();
            dataGridViewTextBoxColumn6 = new DataGridViewTextBoxColumn();
            mainPanel.SuspendLayout();
            toolbarPanel.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)_appsDataGridView).BeginInit();
            _statusStrip.SuspendLayout();
            SuspendLayout();
            // 
            // mainPanel
            // 
            mainPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 20F));
            mainPanel.Controls.Add(toolbarPanel, 0, 0);
            mainPanel.Controls.Add(_appsDataGridView, 0, 1);
            mainPanel.Controls.Add(_statusStrip, 0, 2);
            mainPanel.Location = new Point(0, 0);
            mainPanel.Name = "mainPanel";
            mainPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 40F));
            mainPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 100F));
            mainPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 30F));
            mainPanel.Size = new Size(200, 100);
            mainPanel.TabIndex = 0;
            // 
            // toolbarPanel
            // 
            toolbarPanel.Controls.Add(_addAppButton);
            toolbarPanel.Controls.Add(_editAppButton);
            toolbarPanel.Controls.Add(_removeAppButton);
            toolbarPanel.Controls.Add(_addFromProcessButton);
            toolbarPanel.Controls.Add(_refreshButton);
            toolbarPanel.Controls.Add(_autoStartCheckBox);
            toolbarPanel.Location = new Point(3, 3);
            toolbarPanel.Name = "toolbarPanel";
            toolbarPanel.Size = new Size(194, 34);
            toolbarPanel.TabIndex = 0;
            // 
            // _addAppButton
            // 
            _addAppButton.Location = new Point(0, 0);
            _addAppButton.Name = "_addAppButton";
            _addAppButton.Size = new Size(75, 23);
            _addAppButton.TabIndex = 0;
            _addAppButton.Click += AddAppButton_Click;
            // 
            // _editAppButton
            // 
            _editAppButton.Location = new Point(0, 0);
            _editAppButton.Name = "_editAppButton";
            _editAppButton.Size = new Size(75, 23);
            _editAppButton.TabIndex = 1;
            _editAppButton.Click += EditAppButton_Click;
            // 
            // _removeAppButton
            // 
            _removeAppButton.Location = new Point(0, 0);
            _removeAppButton.Name = "_removeAppButton";
            _removeAppButton.Size = new Size(75, 23);
            _removeAppButton.TabIndex = 2;
            _removeAppButton.Click += RemoveAppButton_Click;
            // 
            // _addFromProcessButton
            // 
            _addFromProcessButton.Location = new Point(0, 0);
            _addFromProcessButton.Name = "_addFromProcessButton";
            _addFromProcessButton.Size = new Size(75, 23);
            _addFromProcessButton.TabIndex = 3;
            _addFromProcessButton.Click += AddFromProcessButton_Click;
            // 
            // _refreshButton
            // 
            _refreshButton.Location = new Point(0, 0);
            _refreshButton.Name = "_refreshButton";
            _refreshButton.Size = new Size(75, 23);
            _refreshButton.TabIndex = 4;
            _refreshButton.Click += RefreshButton_Click;
            // 
            // _autoStartCheckBox
            // 
            _autoStartCheckBox.Location = new Point(0, 0);
            _autoStartCheckBox.Name = "_autoStartCheckBox";
            _autoStartCheckBox.Size = new Size(104, 24);
            _autoStartCheckBox.TabIndex = 5;
            _autoStartCheckBox.CheckedChanged += AutoStartCheckBox_CheckedChanged;
            // 
            // _appsDataGridView
            // 
            _appsDataGridView.Columns.AddRange(new DataGridViewColumn[] { dataGridViewTextBoxColumn1, dataGridViewTextBoxColumn2, dataGridViewTextBoxColumn3, dataGridViewTextBoxColumn4, dataGridViewTextBoxColumn5, dataGridViewTextBoxColumn6 });
            _appsDataGridView.Location = new Point(3, 43);
            _appsDataGridView.Name = "_appsDataGridView";
            _appsDataGridView.Size = new Size(194, 24);
            _appsDataGridView.TabIndex = 1;
            // 
            // _statusStrip
            // 
            _statusStrip.Items.AddRange(new ToolStripItem[] { _statusLabel });
            _statusStrip.Location = new Point(0, 78);
            _statusStrip.Name = "_statusStrip";
            _statusStrip.Size = new Size(200, 22);
            _statusStrip.TabIndex = 2;
            // 
            // _statusLabel
            // 
            _statusLabel.Name = "_statusLabel";
            _statusLabel.Size = new Size(32, 17);
            _statusLabel.Text = "就绪";
            // 
            // dataGridViewTextBoxColumn1
            // 
            dataGridViewTextBoxColumn1.HeaderText = "应用名称";
            dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1";
            // 
            // dataGridViewTextBoxColumn2
            // 
            dataGridViewTextBoxColumn2.HeaderText = "程序路径";
            dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2";
            // 
            // dataGridViewTextBoxColumn3
            // 
            dataGridViewTextBoxColumn3.HeaderText = "参数";
            dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3";
            // 
            // dataGridViewTextBoxColumn4
            // 
            dataGridViewTextBoxColumn4.HeaderText = "启用";
            dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4";
            // 
            // dataGridViewTextBoxColumn5
            // 
            dataGridViewTextBoxColumn5.HeaderText = "运行状态";
            dataGridViewTextBoxColumn5.Name = "dataGridViewTextBoxColumn5";
            // 
            // dataGridViewTextBoxColumn6
            // 
            dataGridViewTextBoxColumn6.HeaderText = "最后检查";
            dataGridViewTextBoxColumn6.Name = "dataGridViewTextBoxColumn6";
            // 
            // MainForm
            // 
            ClientSize = new Size(784, 561);
            Controls.Add(mainPanel);
            Icon = (Icon)resources.GetObject("$this.Icon");
            MinimumSize = new Size(600, 400);
            Name = "MainForm";
            StartPosition = FormStartPosition.CenterScreen;
            Text = "自动启动程序管理器";
            mainPanel.ResumeLayout(false);
            mainPanel.PerformLayout();
            toolbarPanel.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)_appsDataGridView).EndInit();
            _statusStrip.ResumeLayout(false);
            _statusStrip.PerformLayout();
            ResumeLayout(false);
        }

        private void SetupProcessMonitor()
        {
            _processMonitor.AppStatusChanged += OnAppStatusChanged;
        }

        private void SetupNotifyIcon()
        {
            _notifyIcon = new NotifyIcon
            {
                Text = "自动启动程序管理器",
                Visible = false
            };

            // 尝试加载自定义图标，如果失败则使用系统默认图标
            try
            {
                _notifyIcon.Icon = this.Icon;
            }
            catch (Exception ex)
            {
                // 如果加载自定义图标失败，使用系统默认图标
                _notifyIcon.Icon = SystemIcons.Application;
                System.Diagnostics.Debug.WriteLine($"Failed to load custom icon: {ex.Message}");
            }

            _notifyContextMenu = new ContextMenuStrip();
            _notifyContextMenu.Items.Add("显示主窗口", null, (s, e) => ShowMainWindow());
            _notifyContextMenu.Items.Add("退出", null, (s, e) => ExitApplication());

            _notifyIcon.ContextMenuStrip = _notifyContextMenu;
            _notifyIcon.DoubleClick += (s, e) => ShowMainWindow();
        }

        private void LoadConfiguration()
        {
            try
            {
                var (apps, autoStartEnabled) = _configManager.LoadConfig();
                _managedApps = apps;
                _autoStartEnabled = autoStartEnabled;
                _autoStartCheckBox.Checked = autoStartEnabled;

                RefreshDataGridView();
                UpdateStatus("配置已加载");

                // 设置开机自启动
                var currentPath = _startupManager.GetCurrentExecutablePath();
                _startupManager.SetAutoStart(autoStartEnabled, currentPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载配置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                UpdateStatus("配置加载失败");
            }
        }

        private void SaveConfiguration()
        {
            try
            {
                _configManager.SaveConfig(_managedApps, _autoStartEnabled);
                _processMonitor.LoadManagedApps();
                UpdateStatus("配置已保存");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存配置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                UpdateStatus("配置保存失败");
            }
        }

        private void RefreshDataGridView()
        {
            _appsDataGridView.Rows.Clear();
            foreach (var app in _managedApps)
            {
                _appsDataGridView.Rows.Add(
                    app.Name,
                    app.ExecutablePath,
                    app.Arguments,
                    app.IsEnabled ? "是" : "否",
                    app.IsRunning ? "运行中" : "已停止",
                    app.LastChecked.ToString("HH:mm:ss")
                );
            }
        }

        private void UpdateStatus(string message)
        {
            _statusLabel.Text = $"{DateTime.Now:HH:mm:ss} - {message}";
        }

        private void OnAppStatusChanged(object? sender, AppStatusChangedEventArgs e)
        {
            if (InvokeRequired)
            {
                Invoke(new Action(() => OnAppStatusChanged(sender, e)));
                return;
            }

            var app = e.App;
            var statusText = e.IsRunning ? "已启动" : "已停止";
            UpdateStatus($"应用 '{app.Name}' {statusText}");

            // 将 e的状态更新到 _managedApps 列表中
            var existingApp = _managedApps.FirstOrDefault(a => a.Name == app.Name && a.ExecutablePath == app.ExecutablePath);
            if (existingApp != null)
            {
                existingApp.IsRunning = e.IsRunning;
                existingApp.ProcessId = app.ProcessId;
                existingApp.LastChecked = DateTime.Now;
            }
            // 添加调试信息
            System.Diagnostics.Debug.WriteLine($"OnAppStatusChanged: {app.Name} - {statusText} (ProcessId: {app.ProcessId})");

            // 更新数据网格视图
            RefreshDataGridView();
        }

        private void AddAppButton_Click(object? sender, EventArgs e)
        {
            using var dialog = new AddAppDialog();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                _managedApps.Add(dialog.ManagedApp);
                RefreshDataGridView();
                SaveConfiguration();
                UpdateStatus($"已添加应用: {dialog.ManagedApp.Name}");
            }
        }

        private void EditAppButton_Click(object? sender, EventArgs e)
        {
            if (_appsDataGridView.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择要编辑的应用", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var selectedIndex = _appsDataGridView.SelectedRows[0].Index;
            var app = _managedApps[selectedIndex];

            using var dialog = new AddAppDialog(app);
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                _managedApps[selectedIndex] = dialog.ManagedApp;
                RefreshDataGridView();
                SaveConfiguration();
                UpdateStatus($"已更新应用: {dialog.ManagedApp.Name}");
            }
        }

        private void RemoveAppButton_Click(object? sender, EventArgs e)
        {
            if (_appsDataGridView.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择要删除的应用", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var selectedIndex = _appsDataGridView.SelectedRows[0].Index;
            var app = _managedApps[selectedIndex];

            if (MessageBox.Show($"确定要删除应用 '{app.Name}' 吗？", "确认删除", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                _managedApps.RemoveAt(selectedIndex);
                RefreshDataGridView();
                SaveConfiguration();
                UpdateStatus($"已删除应用: {app.Name}");
            }
        }

        private void AddFromProcessButton_Click(object? sender, EventArgs e)
        {
            using var dialog = new ProcessSelectionDialog(_processMonitor.GetRunningProcesses());
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                _managedApps.Add(dialog.ManagedApp);
                RefreshDataGridView();
                SaveConfiguration();
                UpdateStatus($"已从进程添加应用: {dialog.ManagedApp.Name}");
            }
        }

        private async void RefreshButton_Click(object? sender, EventArgs e)
        {
            try
            {
                UpdateStatus("正在检查应用状态...");
                await _processMonitor.CheckAllAppsStatusAsync();
                RefreshDataGridView();
                UpdateStatus("已刷新");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"刷新失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                UpdateStatus("刷新失败");
            }
        }

        private void AutoStartCheckBox_CheckedChanged(object? sender, EventArgs e)
        {
            _autoStartEnabled = _autoStartCheckBox.Checked;
            try
            {
                var currentPath = _startupManager.GetCurrentExecutablePath();
                _startupManager.SetAutoStart(_autoStartEnabled, currentPath);
                SaveConfiguration();
                UpdateStatus(_autoStartEnabled ? "已启用开机自启动" : "已禁用开机自启动");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"设置开机自启动失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                _autoStartCheckBox.Checked = !_autoStartEnabled;
            }
        }

        private void ShowMainWindow()
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.BringToFront();
        }

        private void ExitApplication()
        {
            _processMonitor.StopMonitoring();
            _notifyIcon.Visible = false;
            Application.Exit();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            _processMonitor.StartMonitoring();
            
            // 立即检查一次应用状态
            _ = Task.Run(async () =>
            {
                await _processMonitor.CheckAllAppsStatusAsync();
                if (InvokeRequired)
                {
                    Invoke(new Action(() => RefreshDataGridView()));
                }
            });
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing)
            {
                e.Cancel = true;
                this.Hide();
                _notifyIcon.Visible = true;
                _notifyIcon.ShowBalloonTip(3000, "自动启动程序管理器", "程序已最小化到系统托盘", ToolTipIcon.Info);
            }
            else
            {
                _processMonitor.StopMonitoring();
                _notifyIcon.Visible = false;
            }
            base.OnFormClosing(e);
        }
    }
}